<?php
/**
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/1/25
 * Time: 17:26
 */

namespace App\Services\SortingWeb;

use App\Repositories\Order\OrderInfoRepositoryEloquent;
use Illuminate\Support\Facades\DB;
use App\Services\Orders\OrderService as Order;

class OrderService{
    protected $orderInfoRepositoryEloquent;
    protected $order;


    public function __construct(OrderInfoRepositoryEloquent $orderInfoRepositoryEloquent,
                                Order $order){
        $this->orderInfoRepositoryEloquent = $orderInfoRepositoryEloquent;
        $this->order = $order;
    }

    /**
     * 根据条件查询订单
     * Author:poptser@foxmail.com
     * @param int $area_id  配送区域ID 0为全部
     * @param string $time_id  配送时间段 0为全部
     * @param int $wid      配送商ID 0为全部
     * @param int $order_type   订单类型ID 0普通 1超时免单
     * @param int $company_id    配送日期开始
     * @param string $sorting_date  配送日期结束
     * @return mixed
     */
    public function getOrderPending(int $area_id, string $time_id, int $company_id, $order_type,
                                    string $sorting_date,int $wid){

        //条件总成
        $filter = [];
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['order_info.shipping_id', '=', 3];
        $filter[] = ['order_info.order_status', '<>', 2];
        $filter[] = ['order_info.sorting_id', '=', 0];
        $filter[] = ['order_info.shipping_status', '=', 0];
        $filter[] = ['order_info.outgo', '=', 0];
        $filter[] = ['order_info.freeze_status', '=',0];
        if($area_id>0){
            //划区ID 查询此划区区间得配送区域ID
            $wdrIdArray = DB::table('warehouse_deliver_region')
                ->where([
                    ['zoning_id', '=', $area_id],
                    ['status', '=', '1'],
                ])->pluck('id');
            //$filter[] = ['order_info.wdr_id', 'in', $wdrIdArray];
        }else{
            $wdrIdArray = DB::table('warehouse_deliver_region')
                ->where([
                    ['status', '=', '1'],
                ])->pluck('id');
        }

        //if($wid>0){
            //查询指定仓库
            $filter[] = ['order_info.distribution_company_id', '=', $company_id];
            $filter[] = ['order_info.wid', '=', $wid];
        //}

        if(!empty($sorting_date)){
            //配送开始时间
            if($time_id!=0){
                $time_array = explode("-",$time_id);
                $filter[] = ['order_info.best_time_start', '=', $time_array[0]];
                $filter[] = ['order_info.best_time', '=', $time_array[1]];
                //return $sorting_date." ".$time_array[0]." :00";
            }else{
                $filter[] = ['order_info.best_time_start', '>', strtotime($sorting_date." 00:00:00")];
                $filter[] = ['order_info.best_time', '<=', strtotime($sorting_date." 23:59:59")];
            }
        }


        $order_mode =  DB::table('order_info')
            ->whereIn('order_info.wdr_id',$wdrIdArray)
            ->whereIn('order_info.pay_status', [2, 3])
            ->where($filter)
            ->whereNotNull("order_info.k3cn_sn")
            ->whereNull('sorting_order_link.order_id')
            ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
            ->leftJoin('order_info_free_single', 'order_info.order_id', '=', 'order_info_free_single.order_id')
            ->select(
                [
                    'order_info.order_id',
                    'order_info.order_sn',
                    'order_info.add_time',
                    'order_info.wdr_id',
                    'order_info.distribution_company_id',
                    'order_info.best_time_start',
                    'order_info.best_time',
                ]);



        if($order_type!==false){
            if($order_type>0){
                $order_mode->whereNotNull('order_info_free_single.order_id');
            }else{
                $order_mode->whereNull('order_info_free_single.order_id');
            }
        }
        //DB::enableQueryLog();
        $order_data = $order_mode->paginate()->toArray();
        //return DB::getQueryLog();
        //return $order_data['data'];
        $order_list = [];
        foreach ($order_data['data'] as $key=>$value){
            if($value->distribution_company_id==0){
                $distribution_company = "自配送";
            }else{
                $distribution_company = DB::table('distribution_company')->where('id',$value->distribution_company_id)->value('lite_name');
            }
            if($order_type!==false){
                if($order_type>0){
                    $single_text = "<span style='color: red'>超时免单</span>";
                }else{
                    $single_text = "普通";
                }
            }else{
                $is_single = DB::table('order_info_free_single')->where("order_id","=",$value->order_id)->count();
                if($is_single>0){
                    $single_text = "<span style='color: red'>超时免单</span>";
                }else{
                    $single_text = "普通";
                }

            }

            $order_list[] = [
                'order_id'=>$value->order_id,
                'order_sn'=>$value->order_sn,
                'add_time'=>local_date('Y-m-d H:i:s',$value->add_time),
                'wdr_id'=>DB::table('zoning_cate')
                    ->join('warehouse_deliver_region', 'zoning_cate.id', '=', 'warehouse_deliver_region.zoning_id')
                    ->where('warehouse_deliver_region.id',$value->wdr_id)
                    ->value('zoning_cate.name'),
                'wid'=>$distribution_company,
                'best_time'=>date('Y-m-d H:i',$value->best_time_start)."-".date('H:i',$value->best_time),
                'free_single'=>$single_text,
            ];
            //return $order_list;
        }
        $order_data['data'] = $order_list;
        return $order_data;
    }

    /**
     * 生成拣货单
     * Author:poptser@foxmail.com
     * @param array $order_list
     * @param int $wid
     * @param int $company_id
     * @param int $area_id
     * @param  $best_time
     * @param  $best_date
     * @param  $userId
     * @return bool
     */
    public function generateSortingOrder(array $order_list, int $wid,int $company_id,
                                         int $area_id,$best_time,$best_date,$userId){

        //条件总成
        $filter = [];
        //$filter[] = ['order_id', 'in', $order_list];
        $filter[] = ['wid', '=', $wid];
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['order_info.freeze_status', '=',0];
        //return $filter;
        //DB::enableQueryLog();
        $order_id_list =  DB::table('order_info')
            ->whereIn('pay_status', [2, 3])
            ->where($filter)
            ->whereNotNull("order_info.k3cn_sn")
            ->whereIn('order_id',$order_list)
            ->pluck('order_id')->toArray();
//        $now_send = array_slice($order_id_list,5,10);
//        dump($now_send);
//        exit();

        $ToolService = new ToolService();

        $max_num = $ToolService->getSortingMaxNum($wid);

        $all_sorting_num = ceil(count($order_id_list)/$max_num);
        $best_time_array = explode("-",$best_time);
        //return $all_sorting_num;

        for ($i=0;$i<$all_sorting_num;$i++){
            //本次需要生成的拣货单订单
            $now_send = array_slice($order_id_list,$max_num*$i,$max_num);

            $sortingSn = get_order_sn();
            $sorting_id = DB::table('sorting_order')->insertGetId(
                [
                    'sorting_sn' => $sortingSn,
                    'status' => 1,
                    'ctime' => gm_time(),
                    'user_id' => 1,
                    'wid' => $wid,
                    'best_date' => $best_date,
                    'best_time' => date('H:i',$best_time_array[0])."-".
                        date('H:i',$best_time_array[1]),
                    'area_id' => $area_id,
                    'company_id' => $company_id
                ]
            );
            if($sorting_id>0){
                $order_link_data = [];
                foreach ($now_send as $value){

                    $orderStatus = $this->getOrderStatus($value);
                    $dataAction['order_status'] = $orderStatus->order_status;
                    $dataAction['shipping_status'] = $orderStatus->shipping_status;
                    $dataAction['pay_status'] = $orderStatus->pay_status;
                    $dataAction['action_user'] = $ToolService->getNameById($userId);
                    $dataAction['order_id']=$value;
                    $dataAction['action_note']='已生成拣货单:'.$sortingSn." [ SortingWeb ]";;
                    $dataAction['log_time']=gm_time();
                    $dataAction['user_id']=$userId;
                    $this->order->addOrderAction($dataAction);

                    $order_link_data[] = ['order_id' =>$value, 'sorting_order_id' =>$sorting_id];
                }
                $re = DB::table('sorting_order_link')->insert($order_link_data);
            }
        }

        //sorting_order_link
        //return DB::getQueryLog();

        if($re){
            return $re;
        }else{
            return false;
        }
    }


    /**
     * 拣货单列表
     * Author:poptser@foxmail.com
     * @param int $area_id
     * @param int $company_id
     * @param string $sorting_date
     * @param int $wid
     * @param int $sorting_status
     * @return mixed
     */
    public function getSortingList(int $area_id, $company_id,
                                   string $sorting_date, int $wid, int $sorting_status){
        //条件总成
        $filter = [];
        //
        $filter[] = ['wid', '=', $wid];
        if($area_id>0){
            $filter[] = ['area_id', '=', $area_id];
        }
        if($company_id!==false){
            $filter[] = ['company_id', '=', $company_id];
        }
        if($sorting_status>0){
            $filter[] = ['status', '=', $sorting_status];
        }


        $sorting_data =  DB::table('sorting_order')
            ->whereBetween('ctime', [strtotime($sorting_date." 00:00:00")-28800,
                strtotime($sorting_date." 23:59:59")-28800])
            ->where($filter)
            ->select(
                ['*'])->orderBy("id","desc")->paginate()->toArray();

        array_pop($filter);
        $filter[] = ['status', '=', 1];
        //未配货
        $sorting_data['sorting_original'] = DB::table('sorting_order')
            ->whereBetween('ctime', [strtotime($sorting_date." 00:00:00")-28800,
                strtotime($sorting_date." 23:59:59")-28800])
            ->where($filter)
            ->count();
        //配货中
        array_pop($filter);
        $filter[] = ['status', '=', 3];
        $sorting_data['sorting_ing'] = DB::table('sorting_order')
            ->whereBetween('ctime', [strtotime($sorting_date." 00:00:00")-28800,
                strtotime($sorting_date." 23:59:59")-28800])
            ->where($filter)
            ->count();
        //配货完成
        array_pop($filter);
        $filter[] = ['status', '=', 4];
        $sorting_data['sorting_end'] = DB::table('sorting_order')
            ->whereBetween('ctime', [strtotime($sorting_date." 00:00:00")-28800,
                strtotime($sorting_date." 23:59:59")-28800])
            ->where($filter)
            ->count();


        $sorting_list = [];
        $ToolService = new ToolService();

        foreach ($sorting_data['data'] as $key=>$value){

            $sortingOrderIdList = $this->getOrderBySorting($value->id);
            //return $this->getGoodsNumByOrder($sortingOrderIdList);
            $sorting_list[] = [
                'id'=>$value->id,
                'sorting_sn'=>$value->sorting_sn,
                'ctime'=>local_date('Y-m-d H:i:s',$value->ctime),
                'status'=>$this->sortingToString($value->status),
                'cuser'=>$ToolService->getNameById($value->user_id),    //创建人
                'areaName'=>$ToolService->getAreaName($value->area_id),    //创建人
                'orderNum'=>count($sortingOrderIdList),    //订单数
                'goodsNum'=>$this->getGoodsNumByOrder($sortingOrderIdList)    //订单数
            ];
        }
        $sorting_data['data'] = $sorting_list;
        return $sorting_data;
    }


    /**
     * 根据订单列表获取商品数量
     * Author:poptser@foxmail.com
     * @param array $orderIdList
     * @return mixed
     */
    public function getGoodsNumByOrder(array $orderIdList){
        //DB::enableQueryLog();
        return DB::table('order_goods')
            ->whereIn('order_id',$orderIdList)
            ->sum("goods_number") -
            DB::table('order_goods')
                ->whereIn('order_id',$orderIdList)
                ->sum("refund_number");
        //return DB::getQueryLog();
    }

    /**
     * 根据拣货单ID 获取此拣货单所有的订单ID
     * Author:poptser@foxmail.com
     * @param int $sortingId
     * @return mixed
     */
    public function getOrderBySorting(int $sortingId){
        return DB::table('sorting_order_link')
            ->where([
                ['sorting_order_id','=',$sortingId],
            ])->pluck('order_id')->toArray();
    }

    /**
     * 拣货单状态转文字
     * Author:poptser@foxmail.com
     * @param int $status
     * @return string
     */
    public function sortingToString(int $status){
        switch ($status){
            case "1":
                return "未拣货";
                break;
            case "2":
                return "已获取";
                break;
            case "3":
                return "拣货中";
                break;
            case "4":
                return "已配货";
                break;
            case "5":
                return "取消";
                break;
            default:
                return "未知";
        }
    }

    /**
     * 获取订单列表（ 普通订单 ）
     * Author:poptser@foxmail.com
     * @param  $start_date
     * @param  $end_date
     * @param  $order_sn
     * @param  $wid
     * @return mixed
     */
    public function getNormalOrder( $start_date,  $end_date, $order_sn,  $wid){
        //条件总成
        $filter = [];
        //
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['shipping_id', '=', 3];
        $filter[] = ['order_status', '<>', 2];
        //$filter[] = ['freeze_status', '=', 0];

        if(!empty($order_sn)){
            $filter[] = ['order_sn', 'like', "%".$order_sn."%"];
        }

        $order_data =  DB::table('order_info')
            ->where($filter)
            ->whereNotNull("order_info.k3cn_sn")
            ->whereIn('pay_status', [2, 3])
            ->whereIn('shipping_status', [0,3,5])
//            ->whereNull('sorting_order_link.order_id')
//            ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
            ->select(
                [
                    'order_info.order_id',
                    'order_info.order_sn',
                    'order_info.consignee',
                    'order_info.mobile',
                    'order_info.add_time',
                    'order_info.goods_amount',
                    'order_info.discount',
                    'order_info.bonus',
                    'order_info.shipping_fee',
                    'order_info.order_status',
                    'order_info.shipping_status',
                    'order_info.pay_status',
                ]);
        if(empty($order_sn)){
            $order_data->whereBetween('add_time', [strtotime($start_date), strtotime($end_date." 23:59:59")]);
        }
        $order_data = $order_data->paginate()->toArray();
        $ToolService = new ToolService();
        foreach ($order_data['data'] as $key=>$value){
            $order_data['data'][$key]->order_amount =
                number_format($value->goods_amount -
                $value->discount -
                $value->bonus +
                $value->shipping_fee,2);

            $order_data['data'][$key]->status =
                $ToolService->orderToString($value->order_status)." ".
                $ToolService->shippingToString($value->shipping_status)." ".
                $ToolService->payToString($value->pay_status);

        }
        return $order_data;
    }

    /**
     * 获取订单需延迟得参数
     * Author:poptser@foxmail.com
     * @param int $orderId
     * @return mixed
     */
    public function getDelayOrderInfo(int $orderId){
        $orderInfo = DB::table("order_info")->where('order_id',$orderId)
            ->select(['order_id','order_sn','wdr_id','best_time','best_time_start'])
            ->first();
        //dump($orderInfo);
        $orderInfo->best_time = date('Y-m-d H:i',$orderInfo->best_time_start)." - ".
            date('H:i',$orderInfo->best_time);

        $modeId = DB::table("warehouse_deliver_region")->where('id',$orderInfo->wdr_id)
            ->value('wdtype');
        $orderInfo->delay_time = DB::table("distribution_time")->where('mode_id',$modeId)
            ->select(['start_time','end_time'])
            ->get();

        $orderInfo->delay_reason = [
            '缺货待新货补充',
            '过期待新货补充',
            '次损待新货补充',
            '订单漏送延时',
            '变质待新货补充',
            '取消购买商品',
            '临期待新货补充',
            '客户手机空号',
            '无法拨通客户手机'
        ];
        return $orderInfo;
    }

    /**
     * 移除拣货单管理
     * Author:poptser@foxmail.com
     * @param $orderId
     */
    public function removeSortingOrder($orderId){
        $sortingOrderId = DB::table("sorting_order_link")
            ->where("order_id","=",$orderId)
            ->value("sorting_order_id");
        if($sortingOrderId){
            DB::table("sorting_order_link")->where("order_id","=",$orderId)->delete();

            $orderNum = DB::table("sorting_order_link")
                ->where("sorting_order_id","=",$sortingOrderId)
                ->count();
            if(empty($orderNum)){
                DB::table("sorting_order")
                    ->where("id","=",$sortingOrderId)
                    ->update(['status'=>5]);
            }
        }

    }


    /**
     * 更改订单配送时间
     * Author:poptser@foxmail.com
     * @param $orderId
     * @param $startTime
     * @param $endTime
     * @param $unSorting 1解包 0不解
     * @return bool
     */
    public function setOrderBestTime($orderId, $startTime, $endTime,$unSorting=0){
        $data = [
            'best_time_start' => strtotime($startTime),
            'best_time' => strtotime($endTime),
            'freeze_status' => 0//已延迟订单，取消问题单
        ];
        if($unSorting==1){
            $data['shipping_status'] = 0;
            $data['sorting_id'] = 0;
        }else{
            $result = DB::table('order_info')
                ->where('order_id',"=", $orderId)
                ->value("shipping_status");
            if($result==3){
                $data['shipping_status'] = 0;
                $data['sorting_id'] = 0;
            }
        }

        $result = DB::table('order_info')
            ->where('order_id',"=", $orderId)
            ->update($data);
        if($result==0){
            //更新失败
            return false;
        }else{
            //删除商品异常记录
            $goodsData = [
                'lackNum' => 0,
                'poorNum' => 0
            ];
            DB::table('order_goods')
                ->where('order_id',"=", $orderId)
                ->update($goodsData);
            return true;
        }
    }

    /**
     * 获取商品列表
     * Author:poptser@foxmail.com
     * @param $orderId
     * @param $goodsType 1问题商品  0全部商品
     * @return mixed
     */
    public function getOrderGoods($orderId,$goodsType){
        $goodsModel = DB::table("order_goods")->where('order_id',$orderId);
        if($goodsType==1){
            $goodsModel->where('lackNum', '>', 0)->orWhere('poorNum', '>', 0);
        }
        $goodsList = $goodsModel->where('order_id',$orderId)
            ->select(['rec_id','favourable_info','order_id','goods_id','goods_name','goods_sn','goods_number',
                'goods_price','is_gift','is_quota','giving','refund_number',
                'lackNum','poorNum'])
            ->get();
        $goodsList = json_decode(json_encode($goodsList),true); //对象转为数组
        //$goodsList = (array)$goodsList;
        foreach ($goodsList as $key=>$value){
            if($value['lackNum']>0&&$value['poorNum']>0){
                $goodsList[$key]['poorNum'] = 0;
                $goodsList[$key]['ShowName'] = $goodsList[$key]['goods_name']."<span style='color: red'>「 分拆商品 」↓↓↓</span>";
                $value['lackNum'] = 0;
                $value['ShowName'] = $value['goods_name']."<span style='color: red'>「 分拆商品 」↑↑↑</span>";
                $goodsList[] = $value;
            }else{
                $goodsList[$key]['ShowName'] = $goodsList[$key]['goods_name'];
            }
            $goodsList[$key]['favourableInfo'] = unserialize($value['favourable_info']);
            unset($goodsList[$key]['favourable_info']);
        }
        return $goodsList;
    }

    /**
     * 返回此订单运费
     * Author:poptser@foxmail.com
     * @param $orderId
     * @return mixed
     */
    public function judgmentOrderFee($orderId){
        $shippingFeeInfo = DB::table("order_info")->where('order_id',$orderId)
            ->select(['is_refund_freight','shipping_fee','postscript','quality_id'])->first();
        return $shippingFeeInfo;
    }

    /**
     * 获取订单状态
     * Author:poptser@foxmail.com
     * @param $orderId
     * @return mixed
     */
    public function getOrderStatus($orderId){
        $OrderStatus = DB::table("order_info")->where('order_id',$orderId)
            ->select(['order_status','shipping_status','pay_status'])->first();
        return $OrderStatus;
    }

    /**
     * 获取问题单
     * Author:poptser@foxmail.com
     * @param $startDate   //开始日期
     * @param $endDate      //结束日期
     * @param $questionType //问题类型 1缺货  2次品  3缺货+次品
     * @param $orderSn      //订单号
     * @param $wid      //仓库id
     * @return mixed
     */
    public function getQuestionOrder($startDate, $endDate, $questionType, $orderSn,$wid){
        //条件总成
        $filter = [];
        //
        $filter[] = ['k3cn_sn', '<>', null];
        $filter[] = ['wid', '=', $wid];
        $filter[] = ['shipping_id', '=', 3];
        $filter[] = ['order_status', '<>', 2];
        if($questionType>0){
            $filter[] = ['freeze_status', '=', $questionType];
        }else{
            $filter[] = ['freeze_status', '>', 0];
        }

        if(!empty($orderSn)){
            $filter[] = ['order_sn', 'like', "%".$orderSn."%"];
        }
        //return $filter;
        $order_data =  DB::table('order_info')
            ->where($filter)
            ->whereIn('pay_status', [2, 3])
            ->whereIn('shipping_status', [0,3,5])
            ->select(
                [
                    'order_id',
                    'order_sn',
                    'consignee',
                    'mobile',
                    'add_time',
                    'goods_amount',
                    'discount',
                    'bonus',
                    'shipping_fee',
                    'order_status',
                    'shipping_status',
                    'pay_status',
                    'freeze_status',
                    'freeze_time',
                    'freeze_id',
                ])->orderBy("freeze_time","DESC");
        if(empty($orderSn)){
            $order_data->whereBetween('freeze_time', [strtotime($startDate), strtotime($endDate." 23:59:59")]);
        }
        //DB::enableQueryLog();
        $order_data = $order_data->paginate()->toArray();
        //dump(DB::getQueryLog());
        $ToolService = new ToolService();
        foreach ($order_data['data'] as $key=>$value){

            $questionGood = $this->getQuestionGood($value->order_id);
            $value->QuestionUser = $ToolService->getNameById($value->freeze_id)." 「 ".date("Y-m-d H:i:s",$value->freeze_time)." 」 ";
            $value->GoodsName = "";
            //$value->GoodsD = $questionGood;
            $value->GoodsNum = count($questionGood);
            foreach ($questionGood as $value2){
                $questionNum = $value2->lackNum+$value2->poorNum;
                $value->GoodsName .= $value2->goods_name." [ <span style='color: red'>".$questionNum."</span>  ]<br/>";
            }
        }
        return $order_data;
    }

    /**
     * 获取问题商品
     * Author:poptser@foxmail.com
     * @param $orderId
     * @return mixed
     */
    public function getQuestionGood($orderId){
//        $goodsModel= DB::table("order_goods")->where('order_id','=',$orderId)
//            ->select(['rec_id','order_id','goods_id','goods_name','goods_sn','goods_number',
//                'goods_price','is_gift','is_quota','lackNum','poorNum']);
//
//        $goodsModel->where('lackNum', '>', 0)->orWhere('poorNum', '>', 0);
//
//        $goodsList = $goodsModel->get();
        $goodsList = DB::select("select `rec_id`, `order_id`, `goods_id`, `goods_name`, `goods_sn`, `goods_number`, `goods_price`, `is_gift`, `is_quota`, `lackNum`, `poorNum` from `sdx_order_goods` where `order_id` = ".$orderId." and ( `lackNum` > 0 or `poorNum` > 0 )");
        return $goodsList;

    }

    /**
     * 获取配送公司列表
     * Author:poptser@foxmail.com
     * @param $wid
     * @param $date
     * @return array
     */
    public function getCompanyList($wid, $date){
        $ToolService = new ToolService();
        $company_array = $ToolService->getWarehouse();

        $new_array = array(
            "id"=>0,
            "lite_name"=>"食得鲜"
        );
        $new_array = json_decode(json_encode($new_array));

        $company_array[] = $new_array;

        //条件总成
        $filter = [];
        //
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['order_info.shipping_id', '=', 3];
        $filter[] = ['order_info.order_status', '<>', 2];
        $filter[] = ['order_info.sorting_id', '=', 0];
        $filter[] = ['order_info.shipping_status', '=', 0];
        $filter[] = ['order_info.wid', '=', (int)$wid];
        $filter[] = ['order_info.outgo', '=', 0];
        $filter[] = ['order_info.distribution_company_id', '=',0];
        $filter[] = ['order_info.freeze_status', '=',0];
        //DB::enableQueryLog();

        foreach ($company_array as $key=>$value){
            array_pop($filter);
            $filter[] = ['order_info.distribution_company_id', '=',$value->id];
            $orderNum =  DB::table('order_info')
                ->where($filter)
                ->whereNotNull("order_info.k3cn_sn")
                ->whereIn('order_info.pay_status', [2, 3])
                ->whereBetween('order_info.best_time', [strtotime($date), strtotime($date." 23:59:59")])
                ->whereNull('sorting_order_link.order_id')
                ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
                ->count();
            if($orderNum>0){
                $value->orderNumber = $orderNum;  //今日订单
            }else{
                unset($company_array[$key]);
            }
        }
        return $company_array;
    }

    /**
     * 获取时间列表
     * Author:poptser@foxmail.com
     * @param $wid
     * @param $date
     * @param $companyId
     * @return \Illuminate\Support\Collection
     */
    public function getTimeList($wid, $date, $companyId){
        //条件总成
        $filter = [];
        //
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['order_info.shipping_id', '=', 3];
        $filter[] = ['order_info.order_status', '<>', 2];
        $filter[] = ['order_info.sorting_id', '=', 0];
        $filter[] = ['order_info.shipping_status', '=', 0];
        $filter[] = ['order_info.wid', '=', (int)$wid];
        $filter[] = ['order_info.outgo', '=', 0];
        $filter[] = ['order_info.distribution_company_id', '=',$companyId];
        $filter[] = ['order_info.freeze_status', '=',0];
        //DB::enableQueryLog();

        $timeList =  DB::table('order_info')
            ->where($filter)
            ->whereNotNull("order_info.k3cn_sn")
            ->whereIn('order_info.pay_status', [2, 3])
            ->whereBetween('order_info.best_time', [strtotime($date), strtotime($date." 23:59:59")])
            ->whereNull('sorting_order_link.order_id')
            ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
            ->select(['order_info.best_time_start','order_info.best_time'])
            ->groupBy(['order_info.best_time_start','order_info.best_time'])
            ->get();

        $filter[] = ['order_info.best_time_start', '=',0];
        $filter[] = ['order_info.best_time', '=',0];


        foreach ($timeList as $key=>$value){
            array_pop($filter);
            array_pop($filter);
            $filter[] = ['order_info.best_time_start', '=',$value->best_time_start];
            $filter[] = ['order_info.best_time', '=',$value->best_time];

            $orderNum =  DB::table('order_info')
                ->where($filter)
                ->whereIn('order_info.pay_status', [2, 3])
                ->whereNull('sorting_order_link.order_id')
                ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
                ->count();
            if($orderNum>0){
                $value->orderNumber = $orderNum;  //今日订单
                $value->bestTimeMsg = date("H:i",$value->best_time_start)."-".date("H:i",$value->best_time);  //今日订单
            }else{
                unset($timeList[$key]);
            }
        }
        return $timeList;
    }

    /**
     * 获取区域列表
     * Author:poptser@foxmail.com
     * @param $wid
     * @param $date
     * @param $companyId
     * @param $best_time_start
     * @param $best_time
     * @return \Illuminate\Support\Collection
     */
    public function getAreaList($wid, $date, $companyId, $best_time_start, $best_time){
        //条件总成
        $filter = [];
        //
        //$filter[] = ['order_info.k3cn_sn', '<>', null];
        $filter[] = ['order_info.shipping_id', '=', 3];
        $filter[] = ['order_info.order_status', '<>', 2];
        $filter[] = ['order_info.sorting_id', '=', 0];
        $filter[] = ['order_info.shipping_status', '=', 0];
        $filter[] = ['order_info.wid', '=', (int)$wid];
        $filter[] = ['order_info.outgo', '=', 0];
        $filter[] = ['order_info.distribution_company_id', '=',$companyId];
        $filter[] = ['order_info.best_time_start', '=',$best_time_start];
        $filter[] = ['order_info.best_time', '=',$best_time];
        $filter[] = ['order_info.freeze_status', '=',0];
        //DB::enableQueryLog();

        $areaList =  DB::table('order_info')
            ->where($filter)
            ->whereNotNull("order_info.k3cn_sn")
            ->whereIn('order_info.pay_status', [2, 3])
            ->whereNull('sorting_order_link.order_id')
            ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
            ->leftJoin('warehouse_deliver_region', 'order_info.wdr_id', '=', 'warehouse_deliver_region.id')
            ->select(['warehouse_deliver_region.zoning_id'])
            ->groupBy(['warehouse_deliver_region.zoning_id'])
            ->get();

        //return $areaList;
        $ToolService = new ToolService();

        foreach ($areaList as $key=>$value){

            $wdrIdArray = DB::table('warehouse_deliver_region')
                ->where([
                    ['zoning_id', '=', $value->zoning_id],
                    ['status', '=', '1'],
                ])->pluck('id');


            $orderNum =  DB::table('order_info')
                ->where($filter)
                ->whereIn('order_info.pay_status', [2, 3])
                ->whereIn('order_info.wdr_id',$wdrIdArray)
                ->whereNull('sorting_order_link.order_id')
                ->leftJoin('sorting_order_link', 'order_info.order_id', '=', 'sorting_order_link.order_id')
                ->leftJoin('warehouse_deliver_region', 'order_info.wdr_id', '=', 'warehouse_deliver_region.id')
                ->count();
            if($orderNum>0){
                $value->orderNumber = $orderNum;  //今日订单
                $value->areaName = $ToolService->getAreaName($value->zoning_id);
            }else{
                unset($areaList[$key]);
            }
        }
        return $areaList;
    }

    /**
     * 取消问题单
     * Author:poptser@foxmail.com
     * @param $orderId
     * @return int
     */
    public function setOrderNorm($orderId){
        return DB::table('order_info')
            ->where('order_id', $orderId)
            ->update(['freeze_status' => 0]);
    }
}